package com.wengzw.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wengzw.po.Upload;
import com.wengzw.service.UploadService;
import com.wengzw.utils.DataGridViewResult;
import com.wengzw.vo.UploadVo;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller

public class UploadController {
    @Resource
    private UploadService uploadService;

    @RequestMapping("/Upload")
    public String upload(Upload upload, @RequestParam("file") List<MultipartFile> uploadfile, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 判断所上传文件是否存在
        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            //循环输出上传的文件
            for (MultipartFile file : uploadfile) {
                // 获取上传文件的原始名称
                String originalFilename = file.getOriginalFilename();
                //upload.setFilename(originalFilename);
                // 设置上传文件的保存地址目录
                String dirPath = request.getServletContext().getRealPath("/upload/");
                upload.setFilepath(dirPath);
                File filePath = new File(dirPath);
                //System.out.println(dirPath);
                // 如果保存文件的地址不存在，就先创建目录
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                // 使用UUID重新命名上传的文件名称(上传人_uuid_原始文件名称)
                String newFilename = upload.getUsername() + "_" + originalFilename;
                upload.setFilename(newFilename);
                try {
                    // 使用MultipartFile接口的方法完成文件上传到指定位置
                    file.transferTo(new File(dirPath + newFilename));
                } catch (Exception e) {
                    e.printStackTrace();
                    return "error";
                }
                if (uploadService.addFile(upload) > 0) {
                    map.put("success", true);
                    map.put("message", "添加成功");

                } else {
                    map.put("success", false);
                    map.put("message", "添加失败");
                }

            }
            // 跳转到成功页面
           return "success";
        } else {
            return "error";
        }
    }

    @RequestMapping("/list")
    @ResponseBody
    public DataGridViewResult clientList(UploadVo uploadVo) {

        PageHelper.startPage(uploadVo.getPage(),uploadVo.getLimit());
        //调用分页查询账单列表的方法
        List<Upload> fileList = uploadService.findfileList(uploadVo);
        //创建分页对象
        PageInfo<Upload> pageInfo = new PageInfo<Upload>(fileList);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }

    //修改文件
    @RequestMapping(value = "/updatefile",method = RequestMethod.POST)
    @ResponseBody
    public String updatefile(Upload upload,String filename,String oldname){
        String fileurl = upload.getFilepath();
        //String oldname=fileurl+upload.getFilename();
//        System.out.println(oldname);
//        System.out.println(filename);
//        System.out.println(fileurl);
        String oldFurl = fileurl+oldname;
        String newFurl = fileurl+filename;
        File oldName = new File(oldFurl);
        File newName = new File(newFurl);
        oldName.renameTo(newName);
        Map<String,Object> map = new HashMap<String, Object>();

        if(uploadService.updatefile(upload)>0){
            map.put("success",true);
            map.put("message","修改成功");
        }else{
            map.put("success",false);
            map.put("message","修改失败");
        }
        return JSON.toJSONString(map);
    }

    /*
     * 下载文件
     */
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
                                               String filename) throws Exception{
        //System.out.println(filename);
        // 指定要下载的文件所在路径
        String path = request.getServletContext().getRealPath("/upload/");
       // System.out.println(path);
        // 创建该文件对象
       System.out.println(path+File.separator+filename);
        File file = new File(path+File.separator+filename);
        // 对文件名编码，防止中文文件乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        filename = this.getFilename(request, filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载的方式打开文件
        //request.setCharacterEncoding("UTF-8");
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);
    }


//删除文件
@RequestMapping("/deletefile")
@ResponseBody
public String deletefile(Upload upload){
//    System.out.println(upload.getId());
//      System.out.println(upload.getFilepath()+upload.getFilename());
        File file = new File(upload.getFilepath()+upload.getFilename());
        file.delete();
    Map<String,Object> map = new HashMap<String,Object>();
    if(uploadService.deletefile(upload.getId())>0){
        map.put("success",true);
        map.put("message","删除成功");
    }else{
        map.put("success",false);
        map.put("message","删除失败");
    }
    return JSON.toJSONString(map);
}






    /**
     * 根据浏览器的不同进行编码设置，返回编码后的文件名
     */
    public String getFilename(HttpServletRequest request,
                              String filename) throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示
                return URLEncoder.encode(filename, "UTF-8");
            }
        }
        //火狐等其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

}
